package com.zhengxuetao.website.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhengxuetao.website.domain.Category;
import com.zhengxuetao.website.domain.CategoryExample;
import com.zhengxuetao.website.mapper.CategoryMapper;
import com.zhengxuetao.website.req.CategoryQueryReq;
import com.zhengxuetao.website.resp.CategoryQueryResp;
import com.zhengxuetao.website.resp.PageResp;
import com.zhengxuetao.website.util.CopyUtil;
import com.zhengxuetao.website.util.SnowFlake;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.util.ObjectUtils;

import java.util.List;
@Service
public class CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<CategoryQueryResp> list(CategoryQueryReq req){

        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Category> categoryList=categoryMapper.selectByExample(categoryExample);

        PageInfo<Category> pageInfo=new PageInfo<>(categoryList);
        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        PageResp<CategoryQueryResp> pageResp=new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

       public List<CategoryQueryResp> all() {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList,CategoryQueryResp.class);

        return list;
    }


    public void save(CategoryQueryResp req) {
        Category category = CopyUtil.copy(req,Category.class);
        if (ObjectUtils.isEmpty(req.getId())){
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        }else{
            categoryMapper.updateByPrimaryKey(category);
        }
    }

    public void delete(Long id) { categoryMapper.deleteByPrimaryKey(id); }
}
